package net.lovedna.service {
	import lovedna.framework.core.ICommand;
	import lovedna.framework.mvcs.Actor;
	import lovedna.net.QueueStream;

	import net.lovedna.config.MessageConfig;
	import net.lovedna.config.RequestConfig;
	import net.lovedna.data.IMessage;
	import net.lovedna.data.gamedata.AccountInfo;
	import net.lovedna.event.RequestEvent;
	import net.lovedna.event.SystemEvent;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;

	/**
	 * @author hi
	 */
	public class NetServer extends Actor {
		[Inject]
		public var _requestconfig : RequestConfig;
		[Inject]
		public var _messageConfig : MessageConfig;
		[Inject]
		public var _accountInfo : AccountInfo;
		private var _stream : QueueStream;
//		 private var _url : String = "http://app.lovedna.net/game/";
		 private var _url : String = "http://inswf.sinaapp.com/game/";
//		private var _url : String = "http://127.0.0.1/game/";
		private var _loading : Boolean;
		private var _time:Number;
		public function NetServer() {
			_stream = new QueueStream(10);
			_stream.addEventListener(Event.COMPLETE, streamcomplete);
			_stream.addEventListener(IOErrorEvent.IO_ERROR, iohandler);
			addEventListener(RequestEvent.REQUEST, callhandler, true);
		}

		private function iohandler(event : IOErrorEvent) : void {
		}

		private function callhandler(event : RequestEvent) : void {
			var msg : IMessage = event.msg;
			push(msg);
		}

		private function push(msg : IMessage) : void {
			var content : ByteArray = msg.encode();
			// 协议号
			var protocol : String = _requestconfig.getProtocol(msg);
			// 内容
			var ba : ByteArray = new ByteArray();
			ba.writeInt(_accountInfo.id);
			ba.writeUTF(_accountInfo.access);
			ba.writeBytes(content);
			var request : URLRequest = new URLRequest(_url+"?"+protocol);
			request.data = ba;
			request.method = URLRequestMethod.POST;
			//如果是multipart/form-data 则在自动请求的时候会报错
//			request.contentType = "multipart/form-data";
			request.contentType = "application/octet-stream";
			_stream.load(request);
			_loading = true;
			_time=getTimer();
			tracemsg("开始请求" + protocol);
		}

		private function streamcomplete(event : Event) : void {
			_loading = false;
			var data : ByteArray = _stream.bytes;
			var len : uint = data.length;
			if (len < 4) {
				tracemsg("错误的数据");
				return;
			}
			data.position = 0;
			var errormsg:String = data.readUTFBytes(data.bytesAvailable);
			trace(errormsg);
			data.position = 0;
			while (data.bytesAvailable>0) {
				len = data.readUnsignedInt();
				if(data.bytesAvailable<len){
					tracemsg("解析数据错误");
					return;
				}
				var subdata : ByteArray = new ByteArray();
				data.readBytes(subdata, 0, len);
				unpack(subdata);
			}
		}

		private function unpack(data : ByteArray) : void {
			var protocol : int = data.readUnsignedShort();
			var clazz : Class = _messageConfig.getMessage(protocol);
			if (clazz == null) {
				tracemsg("未找到message映射" + protocol);
				return;
			}
			var msg : IMessage = getInstance(clazz);
			if (msg == null) return;
			try{
				msg.decode(data);
			}catch(e:Error){
				tracemsg("message解析出错" + String(msg));
				return;
			}
			
			var command:Class=_messageConfig.getCommand(protocol);
			if(command){
				var icommand:ICommand=reInject(command);
				icommand.execute();
			}
			tracemsg("耗时(" +(getTimer()-_time)+")" + String(msg));
		}
		private function tracemsg(value:String):void{
			dispatchEvent(new SystemEvent(SystemEvent.TRACE, value));
		}
	}
}
